<!--
 * @Descripttion: 
 * @version: 
 * @Author: mmzhang
 * @Date: 2021-07-21 10:45:02
 * @LastEditTime: 2023-02-21 09:27:40
-->
<template>
  <div class="contract-list flex">
    <div class="organization-left">
      <organization @onSearch="searchFun" @onClear="clearProductId" :saveOrgFlag="saveOrgFlag" :orgCheckId="orgCheckId">
      </organization>
    </div>
    <div class="content-right">
      <div v-show="showStatus">
        <date-search ref="dateSearch" @onResolve="resolveFun"></date-search>
        <dt-search ref="search" :labelWidth="100" @search="searchFunClear"
          @reset="searchFunClear" :xl="5" :xlBtn="8">
        </dt-search>
        <!--统计信息-->
        <order-count ref="orderCount" @onChange="changeCountType"></order-count>
        <!--净值数据-->
        <p class="tip-text" v-if="showNetWorthFlag && countType==0 && adjustCount!=0">
          <Icon type="md-alert" :size="18" color="#FAAD14"
            style="line-height:26px;margin-right:10px;" />
          您所选择的统计周期内存在订单调整，如订单金额或面积与统计数据不同，请查看净值数据
          <span class="view hand" @click="viewNetWorthFun">立即查看</span>
        </p>
        <!--净值文案-->
        <p class="tip-text" v-if="countType!=0">
          <Icon type="md-alert" :size="18" color="#FAAD14"
            style="line-height:26px;margin-right:10px;" />
          查看净值数据时，仅可切换顶部日期，不可进行二次筛选
        </p>
      </div>
      <dt-grid ref="table" :page="page" :onFetch='onFetch'>
        <div class="flex btn-content" slot="btn">
          <Button type="default" @click="changeShow()">{{showStatusTxt}}</Button>
          <Poptip trigger="hover" transfer placement="bottom">
            <Button type="primary" style="margin-left: 8px"
              v-if="unlocking('0208020100')">导出</Button>
            <div slot="content">
              <div class="export-btn hand" @click="exportFun(0)"
                v-if="unlocking('0208020100')">
                全部导出</div>
              <div class="export-btn hand" @click="exportFun(30)"
                v-if="unlocking('0208020100')">
                导出历史未全款订单</div>
              <div class="export-btn hand" @click="exportFun(20)"
                v-if="unlocking('0208020100')">
                导出历史全款订单</div>
            </div>
          </Poptip>
          <Poptip trigger="hover" transfer placement="bottom">
            <Button type="primary" style="margin-left: 8px"
              v-if="unlocking('0208020200')">全号导出</Button>
            <div slot="content">
              <div class="export-btn hand" @click="exportFun(1)"
                v-if="unlocking('0208020200')">
                全部导出</div>
              <div class="export-btn hand" @click="exportFun(31)"
                v-if="unlocking('0208020200')">
                导出历史未全款订单</div>
              <div class="export-btn hand" @click="exportFun(21)"
                v-if="unlocking('0208020200')">
                导出历史全款订单</div>
            </div>
          </Poptip>
          <Button type="primary" @click="operationClick" v-if="unlocking('0208020300')"
            style="margin-left: 8px">查看导出记录</Button>
        </div>
      </dt-grid>
    </div>
    <dt-loading :loading="loading"></dt-loading>
    <!--客户详情-->
    <Modal v-model="detailsFlag" title="客户详情" width="80%" :styles="{top:'5%'}"
      :footer-hide="true">
      <detail-page v-if="detailsFlag" :detailsParams="detailsParams"></detail-page>
    </Modal>
    <operation-record ref="operationRecord"></operation-record>
  </div>
</template>
<script>
  import organization from '@/components/organzation.vue'
  import ConSumColumn from './components/contractColumn'
  import contractMgr from '@/biz/salesForm/contractForm'
  import tool from '@/common/tool.js'
  import detailPage from '../../allCustomersManagement/details.vue'
  import dt from '@dt/dt'
  import watermark from '@/common/waterMark'
  import searchOpt from './components/contractSearch'
  import dateSearch from '@/components/dateSearch.vue'
  import ParamsDate from './components/contractDate.js'
  import orderCount from '../components/orderCount.vue'
  import ParamsCountCon from './components/orderCountCon'
  import subCommonMgr from '@/biz/sales/salesCommon'
  export default {
    data() {
      return {
        loading: false,
        detailsFlag: false,
        detailsParams: {},
        orgId: '',
        level: '',
        searchInfo: {
          status: [], //状态
          productTypes: [], // 产品
          productId: '',
          coopModes: [], // 合作模式
          developerAbbreviations: [], //开发商简称
          sourceChannels: [], // 来源渠道
          isBackDate: false,
          buildingId: null,
          companyId: null,
          housesName: ''
        },
        page: {
          rows: 50,
          current: 1
        },
        filterParams: {},
        checkIndex: 3,
        resolveTime: {
          startTime: '',
          endTime: ''
        },
        countList: [],
        countVal: {},
        containDate: [],
        showStatus: true,
        showStatusTxt: '收起筛选',
        counselorParams: 14623,
        tips: '',
        countType: 0, // 0表示总销
        showNetWorthFlag: false,
        searchNum: 0,
        adjustCount: 0,
        saveOrgFlag:true,
        orgCheckId:null
      }
    },
    components: {
      organization,
      detailPage,
      dateSearch,
      orderCount
    },
    created() {
      this.saveOrgFlag = !dt.memory.get('conSumOrder_params')?false:true
      this.orgCheckId = dt.memory.get('conSumOrder_params')?dt.memory.get('conSumOrder_params').orgId:null
      this.countList = new ParamsCountCon(this).options().countList
      this.countVal = new ParamsCountCon(this).options().countVal
      this.tips = new ParamsCountCon(this).options().tips
    },
    beforeRouteEnter(to, from, next) {
      if (
        !(
          from.name == 'viewContractDetail' ||
          from.name == 'viewRefundOrderDetail' ||
          from.name == 'groupReport' ||
          from.name == 'visitReport' ||
          from.name == 'contractReport' ||
          from.name == 'fullPayReport' || from.name == 'achievementReport'
        )
      )
        dt.memory.remove('conSumOrder_params')
      next()
    },
    beforeRouteLeave(to, from, next) {
      this.retainParamsFun()
      next()
    },
    mounted() {
      let _this = this
      let containDate = []

      // 净值
      this.showNetWorthFlag = this.$route.params.showNetWorthFlag

      let retainParams = dt.memory.get('conSumOrder_params')

      this.$refs.table.init(this, new ConSumColumn(this), {
        userId: retainParams ? retainParams.userId : '',
        workNo: retainParams ? retainParams.workNo : '',
        userName: retainParams ? retainParams.userName : '',
        contractorId: retainParams ? retainParams.userId : ''
      })

      this.$refs.search.init(this.$refs.table, new searchOpt(this).options(), this
        .searchInfo)

      // 初始化
      this.$refs.dateSearch.initOptions(new ParamsDate(this).options())
      this.$nextTick(function() {
        if (retainParams) {
          // 处理展示统计数据
          this.countType = retainParams.countType || 0
          this.resolveCountType()
          this.$refs.orderCount.changeType(this.countType)
          if (this.countType != 0) {
            this.$refs.search.init(this.$refs.table, new searchOpt(this).options(), this
              .searchInfo)
          }

          containDate = retainParams.containDate

          this.$refs.dateSearch.setDateFun(retainParams.checkIndex, retainParams.checkTime,
            containDate)
          let resolveLinkTime = {
            startTime: retainParams.checkTime[0] ? retainParams.checkTime[0] : '',
            endTime: retainParams.checkTime[1] ? retainParams.checkTime[1] : ''
          }

          this.checkIndex = retainParams.checkIndex
          this.resolveTime = resolveLinkTime
          this.containDate = containDate

          Object.keys(this.searchInfo).map(function(key) {
            retainParams[key] && (_this.searchInfo[key] = retainParams[key]) //比较key
          })
          retainParams.rows && (this.page.rows = retainParams.rows)
          retainParams.page && (this.page.current = retainParams.page)
          retainParams.filter && _this.$refs.table.throwFilter().import(retainParams
            .filter)


        } else {
          this.$refs.dateSearch.initDateFun()
        }
      })
      watermark.set()
    },
    methods: {
      viewNetWorthFun() {
        this.countType = 1
        this.$refs.orderCount.changeType(1)
        this.changeCountType(1)
      },
      resolveCountType() {
        if (this.countType == 0) {
          this.countList = new ParamsCountCon(this).options().countList
          this.countVal = new ParamsCountCon(this).options().countVal
          this.tips = new ParamsCountCon(this).options().tips
        } else {
          if (this.countType == 1) {
            this.countList = new ParamsCountCon(this).options().countMoneyList
            this.tips = new ParamsCountCon(this).options().tipsMoney
          } else {
            this.countList = new ParamsCountCon(this).options().countAreaList
            this.tips = new ParamsCountCon(this).options().tipsArea
          }
          this.countVal = new ParamsCountCon(this).options().countActualVal
        }
      },
      changeCountType(countType) {
        this.showNetWorthFlag = false
        this.countType = countType
        // 处理展示统计数据
        this.resolveCountType()

        this.searchInfo = {
          status: [], //状态
          productTypes: [], // 产品
          productId: '',
          coopModes: [], // 合作模式
          developerAbbreviations: [], //开发商简称
          sourceChannels: [], // 来源渠道
          isBackDate: false,
          buildingId: null,
          companyId: null,
          housesName: ''
        }
        this.$refs.table.clearFilter()
        this.$refs.search.init(this.$refs.table, new searchOpt(this).options(), this
          .searchInfo)
        this.loading = true
        this.$refs.table.update(new ConSumColumn(this))
        // 保留订单状态，产品类型参数
        this.searchInfo.status = this.filterParams.status
        this.searchInfo.productTypes = this.filterParams.productTypes
        this.searchInfo.housesName = this.filterParams.housesName
        this.searchInfo.companyId = this.filterParams.companyId
        this.searchInfo.buildingId = this.filterParams.buildingId
        this.$refs.table.fetch()
      },
      changeShow() {
        this.showStatus = !this.showStatus
        this.showStatusTxt = this.showStatus ? '收起筛选' : '展开筛选'
        this.$refs.table.fixHeight()
      },
      operationClick() {
        this.$refs.operationRecord.show('export_contractSummary', "M_17", '', 'logtype')
      },
      resolveFun(checkIndex, resolveTime, containDate) {
        this.checkIndex = checkIndex
        this.resolveTime = resolveTime
        this.containDate = containDate
        this.loading = true
        this.$refs.table.update(new ConSumColumn(this))
        this.$nextTick(function() {
          this.$refs.table.fetch()
        })
      },
      showTips() {
        this.$refs.tipsPage.show()
      },
      getOrderStatistics() {
        //订单净值数据
        if (this.countType || this.showNetWorthFlag) {
          let params = {
            orgId: this.filterParams.orgId,
            buildingId: this.filterParams.level == 4 ? this.filterParams.orgId : null,
            level: this.filterParams.level,
            orderDateType: this.filterParams.orderDateType,
            buildingName: this.filterParams.housesName,
            coopModes: this.filterParams.coopModes,
            endTime: this.filterParams.endDate,
            productId: this.filterParams.productId,
            productTypes: this.filterParams.productTypes,
            companyIds: [],
            startTime: this.filterParams.startDate,
            sourceChannels: this.filterParams.sourceChannels,
            developerAbbreviations: this.filterParams.developerAbbreviations
          }

          subCommonMgr.getOrdernNetWorth(params).then(res => {
            this.loading = false
            if (this.showNetWorthFlag) {
              this.adjustCount = res.subscribeAdjustmentAmount + res
                .subscribeAdjustmentArea + res.contractAdjustmentAmount + res
                .contractAdjustmentArea
            } else {
              this.adjustCount = 0
              this.countVal = { ...res }
              this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
            }
          }).catch(err => {
            this.loading = false
            this.showNetWorthFlag = false
            this.adjustCount = 0
            this.countVal = new ParamsCountCon(this).options().countActualVal
            this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
          })
        }

        // 订单统计数据
        if (this.countType == 0) {
          let params = { ...this.filterParams }
          contractMgr.getContractStatistics(params).then(res => {
            this.loading = false
            this.countVal = { ...res }
            this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
          }).catch(err => {
            this.loading = false
            this.countVal = new ParamsCountCon(this).options().countVal
            this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
          })
        }

      },
      onFetch(data) {
        // 净值提示信息
        if (this.searchNum >= 1) {
          this.showNetWorthFlag = false
        }
        this.searchNum += 1

        if (this.orgId == '' || this.level == '') {
          return new Promise((resolve, reject) => {
            resolve()
          }).then(res => {
            if (this.countType) {
              this.countVal = new ParamsCountCon(this).options().countActualVal
            } else {
              this.countVal = new ParamsCountCon(this).options().countVal
            }
            this.loading = false
            this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
            return {
              list: [],
              total: 0
            }
          })
        } else if (this.checkIndex == null && this.$tool.dateDiff(this.resolveTime.startTime,
            this
            .resolveTime.endTime).Y >= 2) {
          this.$Message.info('自定义日期跨度至多两年')
          return new Promise((resolve, reject) => {
            resolve()
          }).then(res => {
            if (this.countType) {
              this.countVal = new ParamsCountCon(this).options().countActualVal
            } else {
              this.countVal = new ParamsCountCon(this).options().countVal
            }
            this.loading = false
            this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
            return {
              list: [],
              total: 0
            }
          })
        } else {
          data.level = this.level
          data.orgId = this.orgId
          // 处理日期
          data.startDate = this.resolveTime.startTime
          data.endDate = this.resolveTime.endTime
          data.orderDateType = this.containDate

          this.filterParams = {
            ...data
          }

          this.getOrderStatistics()

          return contractMgr
            .getContractSumList(data).then(res => {
              this.$refs.table.fixHeight()
              return res
            }).catch(err => {})
        }
      },
      //清空集团报表isBackDate参数
      searchFunClear() {
        this.page = {
          current: 1,
          total: 0
        }
        this.clearProductId()
      },
      // 搜索
      searchFun(orgCheck) {
        if (orgCheck.orgId == '') {
          return false
        }
        this.page = {
          current: 1,
          total: 0
        }
        this.orgId = orgCheck.orgId ? orgCheck.orgId : this.orgId
        this.level = orgCheck.level ? orgCheck.level : this.level
        this.loading = true
        this.$nextTick(function() {
          this.$refs.table.fetch()
        })
      },
      // 保留列表查询参数
      retainParamsFun() {
        let params = Object.assign({
          checkIndex: this.checkIndex,
          containDate: this.containDate,
          checkTime: [this.resolveTime.startTime, this.resolveTime.endTime],
          filter: this.$refs.table.throwFilter().export(),
          countType: this.countType
        }, this.filterParams)
        dt.memory.set('conSumOrder_params', params)
      },
      // 客户姓名链接到客户资料
      onLinkUser(row) {
        if (row.customerName == '-') {
          return false
        }
        this.detailsFlag = true
        this.detailsParams = {
          customerId: row.customerId, // 手机号唯一编码
          userCustomerId: row.userCustomerId, // 客户信息唯一编码
          buildingId: row.housesId,
          userId: row.userId,
          cityCode: row.cityId,
        }
      },
      // 查看
      viewFun(row) {
        this.$router.push({
          name: 'viewContractDetail',
          query: {
            examineBtn: false,
            orderStatusName: '签约',
            orderNum: row.contractCode, // 单号
            businessId: row.contractId, // 业务id
            buildingId: row.housesId,
            subscriptionId: row.subscriptionId,
            isSummary: true
          },
        })
      },

      // 清空所属产品
      clearProductId() {
        this.searchInfo.productId = ''
        this.searchInfo.coopModes = [] // 合作模式
        this.searchInfo.developerAbbreviations = [] //开发商简称
        this.searchInfo.sourceChannels = [] // 来源渠道
        this.searchInfo.isBackDate = false
      },
      // 导出
      exportFun(exportType) {
        let params = { ...this.filterParams }
        params.exportType = exportType
        params.logDate =
          `${this.resolveTime.startTime.substring(0,10)} - ${this.resolveTime.endTime.substring(0,10)}`

        if (this.checkIndex == null && this.$tool.dateDiff(this.resolveTime.startTime, this
            .resolveTime.endTime).Y >= 2) {
          this.$Message.info('自定义日期跨度至多两年')
          return false
        }

        contractMgr
          .exportContractSum(params)
          .then((res) => {})
          .catch((err) => {})
      }
    },
  }
</script>
<style lang="scss" scoped>
  .contract-list {
    padding: 20px;

    .content-right {
      width: calc(100% - 270px);
    }
  }

  .export-btn {
    line-height: 30px;
    cursor: pointer;
    color: #2d8cf0;
    text-align: center;
    border-bottom: 1px #e8eaec solid;
  }

  .tip-text {
    width: 100%;
    margin: 10px 0;
    line-height: 40px;
    color: #a30014;
    background-color: rgba(254, 252, 236, 1);
  }

  .view {
    margin-left: 20px;
    color: #2d8cf0;
  }
</style>